package com.xy.bizportdemo.task;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

/**
 * Created by admin on 2016/12/28.
 */

public class LoadBaseAsyncTask extends AsyncTask<String, Integer, Void> {
    private static final String TAG = "LoadBaseAsyncTask";

    public static final int STATUS_LOADING = 1;
    public static final int STATUS_FINISH = 2;
    public static final int STATUS_IDLE = 3;
    public static final int STATUS_ERROR = 4;
    public static final int STATUS_LOADED = 5;

    protected int mStatus = STATUS_IDLE;
    protected Context mContext = null;
    private OnLoadCallback mCallback = null;

    public LoadBaseAsyncTask(Context context) {
        super();
        mContext = context;
    }

    public synchronized void setOnLoadCallback(OnLoadCallback callback) {
        mCallback = callback;
        postStatus();
    }

    private synchronized void postStatus() {
        if (mCallback != null) {
            Log.i(TAG, "postStatus: status=" + mStatus);
            mCallback.onStatus(mStatus);
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mStatus = STATUS_LOADING;
        postStatus();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        postStatus();
        mStatus = (mStatus == STATUS_FINISH) ? STATUS_LOADED : STATUS_IDLE;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (mCallback != null) {
            mCallback.onProgress(values[0], values[1]);
        }
    }

    @Override
    protected void onCancelled(Void aVoid) {
        super.onCancelled(aVoid);
        mStatus = STATUS_IDLE;
        postStatus();
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        mStatus = STATUS_IDLE;
        postStatus();
    }

    @Override
    protected Void doInBackground(String... params) {
        mStatus = STATUS_FINISH;
        return null;
    }

    public interface OnLoadCallback {
        void onProgress(int current, int total);
        void onStatus(int status);
    }
}
